import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

public class AnalysisPanel extends JPanel {
    private GradeDAO gradeDAO;
    private StudentDAO studentDAO;
    private CourseDAO courseDAO;
    private JTextArea resultArea;

    public AnalysisPanel() {
        gradeDAO = new GradeDAO();
        studentDAO = new StudentDAO();
        courseDAO = new CourseDAO();
        setLayout(new BorderLayout(10, 10));

        // 结果展示区域
        resultArea = new JTextArea();
        resultArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(resultArea);
        add(scrollPane, BorderLayout.CENTER);

        // 分析按钮面板
        JPanel buttonPanel = new JPanel(new GridLayout(2, 3, 10, 10));

        JButton studentStatsButton = new JButton("学生成绩统计");
        studentStatsButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                analyzeStudentStats();
            }
        });
        buttonPanel.add(studentStatsButton);

        JButton courseStatsButton = new JButton("课程成绩统计");
        courseStatsButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                analyzeCourseStats();
            }
        });
        buttonPanel.add(courseStatsButton);

        JButton classStatsButton = new JButton("班级成绩统计");
        classStatsButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                analyzeClassStats();
            }
        });
        buttonPanel.add(classStatsButton);

        JButton failStudentsButton = new JButton("不及格学生");
        failStudentsButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                findFailStudents();
            }
        });
        buttonPanel.add(failStudentsButton);

        JButton topStudentsButton = new JButton("优秀学生");
        topStudentsButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                findTopStudents();
            }
        });
        buttonPanel.add(topStudentsButton);

        JButton clearButton = new JButton("清空结果");
        clearButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                resultArea.setText("");
            }
        });
        buttonPanel.add(clearButton);

        add(buttonPanel, BorderLayout.NORTH);
    }

    private void analyzeStudentStats() {
        List<Student> students = studentDAO.getAllStudents();
        StringBuilder sb = new StringBuilder();
        sb.append("========== 学生成绩统计 ==========\n");

        for (Student student : students) {
            List<Grade> grades = gradeDAO.getGradesByStudent(student.getStudentId());
            if (!grades.isEmpty()) {
                double total = 0;
                double min = 100;
                double max = 0;

                sb.append("学号: ").append(student.getStudentId())
                        .append(", 姓名: ").append(student.getName()).append("\n");
                sb.append("课程成绩:\n");

                for (Grade grade : grades) {
                    Course course = courseDAO.getCourseById(grade.getCourseId());
                    if (course != null) {
                        sb.append("  ").append(course.getCourseName())
                                .append(": ").append(grade.getScore()).append("\n");

                        total += grade.getScore();
                        if (grade.getScore() < min) min = grade.getScore();
                        if (grade.getScore() > max) max = grade.getScore();
                    }
                }

                double avg = total / grades.size();
                sb.append(String.format("平均分: %.2f, 最低分: %.2f, 最高分: %.2f\n\n", avg, min, max));
            }
        }

        resultArea.setText(sb.toString());
    }

    private void analyzeCourseStats() {
        List<Course> courses = courseDAO.getAllCourses();
        StringBuilder sb = new StringBuilder();
        sb.append("========== 课程成绩统计 ==========\n");

        for (Course course : courses) {
            List<Grade> grades = gradeDAO.getGradesByCourse(course.getCourseId());
            if (!grades.isEmpty()) {
                double total = 0;
                double min = 100;
                double max = 0;
                int failCount = 0;

                sb.append("课程: ").append(course.getCourseName()).append("\n");
                sb.append("选修人数: ").append(grades.size()).append("\n");

                for (Grade grade : grades) {
                    total += grade.getScore();
                    if (grade.getScore() < min) min = grade.getScore();
                    if (grade.getScore() > max) max = grade.getScore();
                    if (grade.getScore() < 60) failCount++;
                }

                double avg = total / grades.size();
                double passRate = (grades.size() - failCount) * 100.0 / grades.size();

                sb.append(String.format("平均分: %.2f, 最低分: %.2f, 最高分: %.2f\n", avg, min, max));
                sb.append(String.format("不及格人数: %d, 及格率: %.2f%%\n\n", failCount, passRate));
            }
        }

        resultArea.setText(sb.toString());
    }

    private void analyzeClassStats() {
        List<Student> students = studentDAO.getAllStudents();
        if (students.isEmpty()) return;

        // 获取所有班级
        java.util.Set<String> classes = new java.util.HashSet<>();
        for (Student student : students) {
            classes.add(student.getClassName());
        }

        StringBuilder sb = new StringBuilder();
        sb.append("========== 班级成绩统计 ==========\n");

        for (String className : classes) {
            double classTotal = 0;
            int classCount = 0;
            int classFailCount = 0;

            sb.append("班级: ").append(className).append("\n");

            for (Student student : students) {
                if (student.getClassName().equals(className)) {
                    List<Grade> grades = gradeDAO.getGradesByStudent(student.getStudentId());
                    if (!grades.isEmpty()) {
                        double studentTotal = 0;
                        int studentFailCount = 0;

                        for (Grade grade : grades) {
                            studentTotal += grade.getScore();
                            if (grade.getScore() < 60) studentFailCount++;
                        }

                        double studentAvg = studentTotal / grades.size();
                        classTotal += studentAvg;
                        classCount++;
                        classFailCount += studentFailCount;
                    }
                }
            }

            if (classCount > 0) {
                double classAvg = classTotal / classCount;
                sb.append(String.format("班级平均分: %.2f\n", classAvg));
                sb.append(String.format("不及格人次: %d\n\n", classFailCount));
            }
        }

        resultArea.setText(sb.toString());
    }

    private void findFailStudents() {
        List<Grade> grades = gradeDAO.getAllGrades();
        java.util.Set<String> failStudents = new java.util.HashSet<>();

        for (Grade grade : grades) {
            if (grade.getScore() < 60) {
                Student student = studentDAO.getStudentById(grade.getStudentId());
                Course course = courseDAO.getCourseById(grade.getCourseId());
                if (student != null && course != null) {
                    failStudents.add(String.format("%s (%s) - %s: %.2f",
                            student.getName(), student.getStudentId(),
                            course.getCourseName(), grade.getScore()));
                }
            }
        }

        StringBuilder sb = new StringBuilder();
        sb.append("========== 不及格学生 ==========\n");
        if (failStudents.isEmpty()) {
            sb.append("没有不及格的学生\n");
        } else {
            for (String info : failStudents) {
                sb.append(info).append("\n");
            }
        }

        resultArea.setText(sb.toString());
    }

    private void findTopStudents() {
        List<Student> students = studentDAO.getAllStudents();
        java.util.Map<String, Double> studentAverages = new java.util.HashMap<>();

        // 计算每个学生的平均分
        for (Student student : students) {
            List<Grade> grades = gradeDAO.getGradesByStudent(student.getStudentId());
            if (!grades.isEmpty()) {
                double total = 0;
                for (Grade grade : grades) {
                    total += grade.getScore();
                }
                studentAverages.put(student.getStudentId(), total / grades.size());
            }
        }

        // 按平均分排序
        List<java.util.Map.Entry<String, Double>> sorted = new java.util.ArrayList<>(studentAverages.entrySet());
        sorted.sort(java.util.Map.Entry.comparingByValue(java.util.Collections.reverseOrder()));

        StringBuilder sb = new StringBuilder();
        sb.append("========== 优秀学生 (平均分前10名) ==========\n");

        int count = Math.min(10, sorted.size());
        for (int i = 0; i < count; i++) {
            String studentId = sorted.get(i).getKey();
            double avg = sorted.get(i).getValue();
            Student student = studentDAO.getStudentById(studentId);
            if (student != null) {
                sb.append(String.format("%d. %s (%s): %.2f\n",
                        i+1, student.getName(), student.getStudentId(), avg));
            }
        }

        resultArea.setText(sb.toString());
    }
}
